package nl.utwente.eemcs.common.analysis;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import nl.utwente.eemcs.common.helpers.DataEdgeType;
import nl.utwente.eemcs.graph.CommunicatorNode;
import nl.utwente.eemcs.graph.Edge;
import nl.utwente.eemcs.graph.EdgeType;
import nl.utwente.eemcs.graph.Graph;
import nl.utwente.eemcs.graph.GraphCollaboration;


public class DataEdgeFixer {
	public static void fixDataEdges(GraphCollaboration gc) {
		HashSet<Edge> dataEdges = collectAllDataEdges(gc);
		for (Edge e : dataEdges) {
			if (e.getEnd() instanceof CommunicatorNode)
				e.addAttribute("relationType", DataEdgeType.Read);
		}
	}
	
	/**
	 * Collects all the data edges that were defined
	 * @return List with all the data edges
	 */
	private static HashSet<Edge> collectAllDataEdges(GraphCollaboration collaboration) {
		HashSet<Edge> edges = new HashSet<Edge>();
		edges.addAll(getDataEdges(collaboration.getMainProcess()));
		for (Graph g : collaboration.getProcesses())
			edges.addAll(getDataEdges(g));
		return edges;
	}
	
	/**
	 * Get the data edges within a graph
	 * @param g Graph
	 * @return List with data edges
	 */
	private static List<Edge> getDataEdges(Graph g) {
		List<Edge> result = new ArrayList<Edge>();
		for (Graph subGraph : g.getAllGraphsAndSubGraphs())
			result.addAll(subGraph.getEdges(EdgeType.Data));
		return result;
	}	
}
